package client.comm.baoding.adapter

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.databinding.DataBindingUtil
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import client.comm.baoding.R
import client.comm.baoding.adapter.main.HomeGood1j4Adapter
import client.comm.baoding.api.bean.GoodsIndex
import client.comm.baoding.databinding.*
import client.comm.baoding.ui.*
import client.comm.baoding.widget.HorizontalPageLayoutManager
import client.comm.baoding.widget.PagingScrollHelper
import client.comm.commlib.base.PagingViewHoder
import client.comm.commlib.base.SyBannerAdapter
import client.comm.commlib.getScreenWidth
import com.bumptech.glide.RequestManager
import com.bumptech.glide.request.RequestOptions
import com.youth.banner.indicator.CircleIndicator

class SyPagingHeaderAdapter(val manager: RequestManager, val context: Context) :
    LoadStateAdapter<PagingViewHoder>(), PagingScrollHelper.onPageChangeListener {

    lateinit var goodsIndex: GoodsIndex

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): PagingViewHoder {
        return PagingViewHoder(
            DataBindingUtil.inflate(
                LayoutInflater.from(parent.context),
                R.layout.pagingitem_syheader,
                parent,
                false
            )
        ).apply {
            val itemBinding = this.binding as PagingitemSyheaderBinding
            itemBinding.event = this@SyPagingHeaderAdapter

            val width = getScreenWidth(parent.context)
            val params: ViewGroup.LayoutParams = itemBinding.banner.getLayoutParams()
            with(itemBinding) {
                params.height = (width / 2.6f).toInt()//2.8、2.25f
                banner.setLayoutParams(params)
                banner.setIndicator(CircleIndicator(context))
                myMarquee.isSelected = true

//                var strBuilder: StringBuilder? = null
//                goodsIndex.article_list.forEach {
//                    strBuilder!!.append(it.title + " ")
//                }
//                var strs: String? = ""
//                goodsIndex.article_list.forEach {
//                    strs += it.title + " "
////                    it.title.reduce { acc, str ->
////                        acc + str
////                    }
//                }
                goodsIndex.article_list?.let {
                    if (it.size != null && it.size > 0) {
                        myMarquee.text = it[0].title
                    }
                }
            }
        }
    }

    override fun onBindViewHolder(holder: PagingViewHoder, loadState: LoadState) {
        val binding = holder.binding as PagingitemSyheaderBinding

        val list = goodsIndex.banner_list
        binding.banner.setAdapter(object : SyBannerAdapter<GoodsIndex.Banner>(list) {
            override fun onBindView(
                holder: BannerViewHolder?,
                data: GoodsIndex.Banner?,
                position: Int,
                size: Int
            ) {
                manager.load(data?.image_url)
                    .apply(RequestOptions().error(R.mipmap.ic_launcher)).into(
                        holder!!.imageView
                    )
            }
        })
        binding.banner.start()

        goodsIndex.category_list_index?.let {
            var ma = GridLayoutManager(context, 2)
            ma.orientation = GridLayoutManager.VERTICAL
            binding.rvGrid14.layoutManager = ma
            var adapter1j4 = HomeGood1j4Adapter(context, manager)
            binding.rvGrid14.adapter = adapter1j4
            if (it.size >= 2) {
                adapter1j4.submitList(it)
                ma.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                    override fun getSpanSize(position: Int): Int {
//                        if (position == 0) {
//                            return 2
//                        }
                        return 1
                    }
                }
            }
        }


        var jx_size = goodsIndex.jx_goods_list.size
        //生成相应数量的导航小圆点
        val params =
            LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        //设置小圆点左右之间的间隔
        params.setMargins(10, 0, 10, 0)
        //得到页面个数
        dotViews = arrayOfNulls(jx_size) //我这里是固定的六页  也可以根据自己需要设置圆点个数
        binding.llIndicator.removeAllViews()
        for (i in 0 until jx_size) {
            val imageView = ImageView(context)
            imageView.layoutParams = params
            imageView.setImageResource(R.drawable.gry_circle) //初始化六个灰色Img
            if (i == 0) {
                //默认启动时，选中第一个小圆点
                imageView.isSelected = true
            } else {
                imageView.isSelected = false //其他的设置不选择
            }
            //得到每个小圆点的引用，用于滑动页面时，（onPageSelected方法中）更改它们的状态。
            dotViews[i] = imageView
            dotViews[0]!!.setImageResource(R.drawable.red_circle) //设置第一个页面选择
            //添加到布局里面显示
            binding.llIndicator.addView(imageView) //这里的img_layout就是我在布局中写的一个Linear Layout用来存放这些圆点img
        }

        if (goodsIndex.jx_goods_list.isNotEmpty()) {
            var adapter = JxGood2Adapter(context, manager) //设置适配器
            adapter.submitList(goodsIndex.jx_goods_list)
            binding.rvJx.adapter = adapter

            val scrollHelper = PagingScrollHelper() //初始化横向管理器
            val horizontalPageLayoutManager = HorizontalPageLayoutManager(1, 1) //这里两个参数是行列，这里实现的是一行三列

            scrollHelper.setUpRecycleView(binding.rvJx) //将横向布局管理器和recycler view绑定到一起
            scrollHelper.setOnPageChangeListener(this) //设置滑动监听
            binding.rvJx.layoutManager = horizontalPageLayoutManager //设置为横向

            scrollHelper.updateLayoutManger()
            scrollHelper.scrollToPosition(0) //默认滑动到第一页
            binding.rvJx.setHorizontalScrollBarEnabled(true)

            //获取总页数,采用这种方法才能获得正确的页数。否则会因为RecyclerView.State 缓存问题，页数不正确。
//            binding.rvJx.post(Runnable { refreshPoint(viewHolder, scrollHelper.pageCount, 0) })

//            var adapter = JxGood2Adapter(context, manager)
//            adapter.submitList(goodsIndex.jx_goods_list)
//            var ma = GridLayoutManager(context, 1)
//            ma.orientation = GridLayoutManager.HORIZONTAL
//            binding.rvJx.layoutManager = ma
//            binding.rvJx.adapter = adapter

        }

//        goodsIndex.tj_goods_list?.let {
//            var adapter = TjGoodAdapter(context, manager)
//            adapter.submitList(it)
//            var ma = LinearLayoutManager(context)
//            ma.orientation = LinearLayoutManager.VERTICAL
//            binding.rvTj.addItemDecoration(SpaceItemDecoration(10))
//            binding.rvTj.layoutManager = ma
//            binding.rvTj.adapter = adapter
//        }

        //旧分类
        /* val types = goodsIndex.category_list
         var index = 0
         if (types != null && types.size > 0) {
             binding.cateWrap.removeAllViews()
             val count: Int = types.size / 5 + if (types.size % 5 == 0) 0 else 1
             for (i in 0 until count) {
                 val tabBinding = DataBindingUtil.inflate<LayoutSyPagtypeBinding>(
                     LayoutInflater.from(context),
                     R.layout.layout_sy_pagtype,
                     binding.cateWrap,
                     false
                 )
                 tabBinding.event = this
                 binding.cateWrap.addView(tabBinding.root)
                 if (index >= types.size) break
                 var bean = types.get(index)
                 tabBinding.oneTxt = bean
                 manager.load(bean.small_img)
                     .apply(RequestOptions().error(R.mipmap.ic_launcher))
                     .into(tabBinding.imgOne)
                 index++
                 if (index >= types.size) break
                 bean = types.get(index)
                 tabBinding.twoTxt = bean
                 manager.load(bean.small_img)
                     .apply(RequestOptions().error(R.mipmap.ic_launcher))
                     .into(tabBinding.twoImg)
                 index++
                 if (index >= types.size) break
                 bean = types.get(index)
                 tabBinding.threeTxt = bean
                 manager.load(bean.small_img)
                     .apply(RequestOptions().error(R.mipmap.ic_launcher))
                     .into(tabBinding.imgThree)
                 index++
                 if (index >= types.size) break
                 bean = types.get(index)
                 tabBinding.fourTxt = bean
                 manager.load(bean.small_img)
                     .apply(RequestOptions().error(R.mipmap.ic_launcher))
                     .into(tabBinding.imgFour)
                 index++
                 if (index >= types.size) break
                 bean = types.get(index)
                 tabBinding.fiveTxt = bean
                 manager.load(bean.small_img)
                     .apply(RequestOptions().error(R.mipmap.ic_launcher))
                     .into(tabBinding.imgFive)
                 index++
             }
         }*/


    }

    lateinit var dotViews: Array<ImageView?> //创建存放图片集合


//    var labelClick: ((bean: GoodsIndex.Category?) -> Unit)? = null
//
//    fun label(bean: GoodsIndex.Category?) {
//        labelClick?.invoke(bean)
//    }


    fun itemClick(bean: GoodsIndex.JxGoods) {
        context.startActivity(Intent(context, GoodsDetailActivity::class.java).apply {
            putExtra("goodsId", "${bean.goods_id}")
        })
    }

    override fun onViewAttachedToWindow(holder: PagingViewHoder) {
        super.onViewAttachedToWindow(holder)
        val lp: ViewGroup.LayoutParams = holder.itemView.getLayoutParams()
        if (lp != null && lp is StaggeredGridLayoutManager.LayoutParams
        ) {
            lp.isFullSpan = true
        }
    }

    // true显示无论什么状态都显示
    override fun displayLoadStateAsItem(loadState: LoadState): Boolean {
        return super.displayLoadStateAsItem(loadState) || (loadState.endOfPaginationReached)
    }

    //购物车
    fun onShopCart(position: Int) {
        changeMainTab?.invoke(position)
    }


    //权益中心
    fun onMenu1() {
        if (notEmptyCatesBtn()) {
            if (goodsIndex.category_btn.size >= 1) {
                val id = goodsIndex.category_btn[0].id
                if (id.isEmpty()) {
                    return
                }
                context.startActivity(Intent(context, TabOne2Activity::class.java).apply {
                    putExtra("title_name", "权益中心")
                    putExtra("cate_id", id)
                    putExtra("position", 0)
                })
            }


        }
    }

    //新手福利
    fun onMenu2() {
        if (notEmptyCatesBtn()) {
            if (goodsIndex.category_btn.size >= 2) {
                val id = goodsIndex.category_btn[1].id
                if (id.isEmpty()) {
                    return
                }
                context.startActivity(Intent(context, TabOne2Activity::class.java).apply {
                    putExtra("title_name", "新手福利")
                    putExtra("cate_id", id)
                    putExtra("position", 1)

                })
            }
        }

    }

    //会员专享
    fun onMenu3() {
        if (notEmptyCatesBtn()) {
            if (goodsIndex.category_btn.size >= 3) {
                val id = goodsIndex.category_btn[2].id
                if (id.isEmpty()) {
                    return
                }
                context.startActivity(Intent(context, TabOne2Activity::class.java).apply {
                    putExtra("title_name", "会员专享")
                    putExtra("cate_id", id)
                    putExtra("position", 2)
                })
            }
        }
    }


    fun onZhaoShangZx() {
        context.startActivity(Intent(context, TabOne3Activity::class.java).apply {
            putExtra("title_name", "招商中心")
            putExtra("type", 0)
        })

    }

    fun onCustomerCenter() {
        context.startActivity(Intent(context, TabOne3Activity::class.java).apply {
            putExtra("title_name", "客服中心")
            putExtra("type", 1)
        })
    }

    //限时特卖
    fun onMenu4() {
        if (notEmptyCatesBtn()) {
            if (goodsIndex.category_btn.size >= 4) {
                val id = goodsIndex.category_btn[3].id
                if (id.isEmpty()) {
                    return
                }
                context.startActivity(Intent(context, TabOne2Activity::class.java).apply {
                    putExtra("title_name", "限时特卖")
                    putExtra("cate_id", id)
                    putExtra("position", 3)
                })
            }
        }
    }

//    fun onJifenNew22(position: Int) {
//        var title = when (position) {
//            1 -> "权益中心"
//            2 -> "新手福利"
//            else -> "限时特卖"
//        }
//        if (notEmptyCatesBtn()) {
//            val id = goodsIndex.category_btn[1].id
//            if (id.isEmpty()) {
//                return
//            }
//            context.startActivity(Intent(context, TabOne2Activity::class.java).apply {
//                putExtra("title_name", title)
//                putExtra("cate_id", id)
//                putExtra("position", 1)
//
//            })
////            toast("$id")
//        }
//    }


    fun onRankList() {
        context.startActivity(Intent(context, FxRankListActivity::class.java))

    }

    /**
     *  goodsIndex.category_btn 不等于null
     */
    fun notEmptyCatesBtn(): Boolean {
        return goodsIndex.category_btn != null && goodsIndex.category_btn.isNotEmpty()
    }

    fun tuiguang() {
        context.startActivity(Intent(context, TuiGuangActivity::class.java))
    }

    var changeMainTab: ((position: Int) -> Unit)? = null
    var changeCheckTab: ((position: Int) -> Unit)? = null
    var notice: ((ArrayList<GoodsIndex.Article>) -> Unit)? = null

    fun changeCheckTab(position: Int) {
        changeCheckTab?.invoke(position)
    }

    fun goNotice() {
        notice?.invoke(goodsIndex.article_list)
    }

    override fun onPageChange(index: Int) {
        //这里是配合圆点指示器实现的，可以忽略
        dotViews?.let {
            for (i in 0 until dotViews.size) {
                if (index === i) {
                    dotViews.get(i)!!.setSelected(true)
                    dotViews.get(i)!!.setImageResource(R.drawable.red_circle)
                } else {
                    dotViews.get(i)!!.setSelected(false)
                    dotViews.get(i)!!.setImageResource(R.drawable.gry_circle)
                }
            }
        }

    }

}